/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.common;

import com.inspur.edp.web.common.io.FileUtility;
import com.inspur.edp.web.common.logger.WebLogger;
import com.inspur.edp.web.common.utility.StringUtility;
import lombok.Data;
import org.apache.commons.io.IOUtils;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 用于进行mac 的拷贝
 *
 * @author noah
 * 2023/7/17 10:23
 */
public class CopyJarFile {
    @Test
    public void copy() throws XmlPullParserException, IOException {
        // 获取当前运行目录
        String currentWorkPath = System.getProperty("user.dir");
        System.out.println(currentWorkPath);
        // 获取对应的工程路径
        String projectPath = new File(currentWorkPath).getParent();
        System.out.println(projectPath);

        // 挨个读取其生成的jar包，拷贝至目标目录
        String version = "0.1.9-SNAPSHOT";

        String baseTargetJarPath = FileUtility.combine(projectPath, "out");

        FileUtility.deleteFolder(baseTargetJarPath);

        Model pomModel = getPom(projectPath);

        Map<String, ModulePath> moduleMap = this.getModulePath();

        pomModel.getModules().forEach((moduleItem) -> {
            copyWithSpecificModule(projectPath, version, baseTargetJarPath, moduleMap, moduleItem);


        });

        Model appConfigPomModel = getPom(FileUtility.combine(projectPath, "appconfig"));
        appConfigPomModel.getModules().forEach((moduleItem) -> {
            copyWithSpecificModule(projectPath, version, baseTargetJarPath, moduleMap, moduleItem);
        });
        Model approvalFormatPomModel = getPom(FileUtility.combine(projectPath, "approval-format"));
        approvalFormatPomModel.getModules().forEach((moduleItem) -> {
            copyWithSpecificModule(projectPath, version, baseTargetJarPath, moduleMap, moduleItem);
        });

        Model formProcessPomModel = getPom(FileUtility.combine(projectPath, "form-process"));
        formProcessPomModel.getModules().forEach((moduleItem) -> {
            copyWithSpecificModule(projectPath, version, baseTargetJarPath, moduleMap, moduleItem);
        });

        Model metadataPomModel = getPom(FileUtility.combine(projectPath, "metadata"));
        metadataPomModel.getModules().forEach((moduleItem) -> {
            copyWithSpecificModule(projectPath, version, baseTargetJarPath, moduleMap, moduleItem);
        });

        Model npmPackagePomModel = getPom(FileUtility.combine(projectPath, "npmpackage"));
        npmPackagePomModel.getModules().forEach((moduleItem) -> {
            copyWithSpecificModule(projectPath, version, baseTargetJarPath, moduleMap, moduleItem);
        });

        Model runtimePomModel = getPom(FileUtility.combine(projectPath, "runtime"));
        runtimePomModel.getModules().forEach((moduleItem) -> {
            copyWithSpecificModule(projectPath, version, baseTargetJarPath, moduleMap, moduleItem);
        });

        Model scriptcachePomModel = getPom(FileUtility.combine(projectPath, "scriptcache"));
        scriptcachePomModel.getModules().forEach((moduleItem) -> {
            copyWithSpecificModule(projectPath, version, baseTargetJarPath, moduleMap, moduleItem);
        });

        Model tsFilePomModel = getPom(FileUtility.combine(projectPath, "tsfile"));
        tsFilePomModel.getModules().forEach((moduleItem) -> {
            copyWithSpecificModule(projectPath, version, baseTargetJarPath, moduleMap, moduleItem);
        });
    }

    private static void copyWithSpecificModule(String projectPath, String version, String baseTargetJarPath, Map<String, ModulePath> moduleMap, String moduleItem) {
        if (moduleMap.containsKey(moduleItem)) {
            String moduleId = moduleMap.get(moduleItem).moduleId;
            if (StringUtility.isNullOrEmpty(moduleId)) {
                WebLogger.Instance.error("无法找到对应的moduleId" + moduleItem);
            } else {
                String modulePath = FileUtility.combine(projectPath, StringUtility.convertNullToEmptyString(moduleMap.get(moduleItem).moduleIdPath), moduleItem);
                String moduleJarFilePath = FileUtility.combine(modulePath, "target", moduleId + "-" + version + ".jar");
                if (!new File(moduleJarFilePath).exists()) {
                    WebLogger.Instance.error("目标文件不存在，" + moduleJarFilePath);
                } else {
                    String targetJarPath = FileUtility.combine(baseTargetJarPath, moduleMap.get(moduleItem).getRelativePath());
                    String targetJarFilePath = FileUtility.combine(targetJarPath, moduleId + ".jar");
                    FileUtility.copyFile(moduleJarFilePath, targetJarFilePath, true);
                    WebLogger.Instance.info("copy file " + moduleJarFilePath + "  to  " + targetJarFilePath);
                }
            }
        }
    }

    private Map<String, ModulePath> getModulePath() {
        Map<String, ModulePath> moduleMap = new HashMap<>();

        moduleMap.put("web-approval-format-api", ModulePath.init("web-approval-format-api", "server/platform/runtime/bcc/libs", "approval-format"));
        moduleMap.put("web-approval-format-core", ModulePath.init("web-approval-format-core", "server/platform/runtime/bcc/libs", "approval-format"));
        moduleMap.put("web-approval-format-rpc", ModulePath.init("web-approval-format-rpc", "server/platform/common/libs", "approval-format"));

        moduleMap.put("web-common", ModulePath.init("web-jitengine-common"));
        moduleMap.put("web-form-metadata-api", ModulePath.init("web-jitengine-formmetadata-api"));
        moduleMap.put("web-form-metadata", ModulePath.init("web-jitengine-formmetadata"));
        moduleMap.put("web-sourcecode-metadata", ModulePath.init("web-sourcecode-metadata", "server/platform/common/libs", "metadata"));
        moduleMap.put("web-pageflow-metadata", ModulePath.init("web-pageflow-metadata", "server/platform/common/libs", "metadata"));
        moduleMap.put("web-appconfig-api", ModulePath.init("web-appconfig-api", "server/platform/common/libs", "appconfig"));
        moduleMap.put("web-appconfig-core", ModulePath.init("web-appconfig-core", "server/platform/common/libs", "appconfig"));
        moduleMap.put("web-frontendproject", ModulePath.init("web-jitengine-frontendproject"));
        moduleMap.put("web-frontendproject-api", ModulePath.init("web-jitengine-frontendproject-api"));
        moduleMap.put("web-form-jitengine", ModulePath.init("web-jitengine"));
        moduleMap.put("web-designschema", ModulePath.init("web-designschema"));
        moduleMap.put("web-designschema-api", ModulePath.init("web-designschema-api"));
        moduleMap.put("web-statemachine", ModulePath.init("web-statemachine-metadata", "server/platform/common/libs", "metadata"));
        moduleMap.put("web-tsfile-api", ModulePath.init("web-tsfile-api", "server/platform/common/libs", "tsfile"));
        moduleMap.put("web-tsfile-core", ModulePath.init("web-tsfile-core", "server/platform/common/libs", "tsfile"));
        moduleMap.put("web-ide-api", ModulePath.init("web-ide-api"));
        moduleMap.put("web-ide-webapi", ModulePath.init("ide-config-webapi", "server/platform/dev/main/libs", ""));
        moduleMap.put("runtime-api", ModulePath.init("web-jitengine-runtimebuild-api", "server/platform/common/libs", "runtime"));
        moduleMap.put("runtime-core", ModulePath.init("web-jitengine-runtimebuild-core", "server/platform/common/libs", "runtime"));
        moduleMap.put("runtime-scriptcache", ModulePath.init("web-jitengine-runtimebuild-scriptcache", "server/platform/common/libs", "scriptcache"));
        moduleMap.put("runtime-scriptcache-api", ModulePath.init("web-jitengine-runtimebuild-scriptcache-api", "server/platform/common/libs", "scriptcache"));
        moduleMap.put("jitengine-web-api", ModulePath.init("web-jitengine-web-api"));
        moduleMap.put("jitengine-web-core", ModulePath.init("web-jitengine-web-core"));
        moduleMap.put("web-npmpackage-core", ModulePath.init("web-npmpackage-core", "server/platform/common/libs", "npmpackage"));
        moduleMap.put("web-npmpackage-api", ModulePath.init("web-npmpackage-api", "server/platform/common/libs", "npmpackage"));
//        moduleMap.put("web-npmpackage-patch", ModulePath.init("web-npmpackage-patch", "server/platform/common/libs", "npmpackage"));
//        moduleMap.put("web-dynamic-form-api", ModulePath.init("web-dynamicform-api"));
//        moduleMap.put("web-dynamic-form-core", ModulePath.init("web-dynamicform-core"));
//        moduleMap.put("web-formconfig-api", ModulePath.init("web-formconfig-api"));
//        moduleMap.put("web-formconfig-core", ModulePath.init("web-formconfig-core"));
        return moduleMap;
    }

    @Data
    private static class ModulePath {
        private String moduleId;
        private String relativePath = "server/platform/common/libs";
        private String moduleIdPath;

        public static ModulePath init(String moduleId) {
            ModulePath modulePath = new ModulePath();
            modulePath.moduleId = moduleId;
            return modulePath;
        }

        public static ModulePath init(String moduleId, String relativePath, String moduleIdPath) {
            ModulePath modulePath = new ModulePath();
            modulePath.moduleId = moduleId;
            modulePath.relativePath = relativePath;
            modulePath.moduleIdPath = moduleIdPath;
            return modulePath;
        }
    }

    private Model getPom(String basePath) throws IOException, XmlPullParserException {
        File file = new File(basePath, "pom.xml");
        FileReader reader = null;

        try {
            reader = new FileReader(file);
            return new MavenXpp3Reader().read(reader);
        } finally {
            IOUtils.closeQuietly(reader);
        }

    }

}
